#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

#include "user_io.h"
#include "user_threads.h"
#include "user_threads_inner.h"

int uthread_open(const char * filename, int flags)
{
    uthread_init();
    
	if (filename == NULL)
		return -1;

	return open(filename, flags | O_NONBLOCK);
}

int uthread_pipe(int filedes[2])
{
// filedes[0] - read
// fildes[1] - write

    uthread_init();

	if (filedes == NULL)
		return -1;

	if (pipe(filedes) == 0) {
        int i;
        
		for (i = 0; i < 2; i++) {
			int flags = fcntl(filedes[i], F_GETFL);
			fcntl(filedes[i], F_SETFL, flags | O_NONBLOCK);
		}
        
        return 0;
	}

    return -1;
}

int uthread_read(int fd, void * buf, size_t count)
{
	int ret;
    
    uthread_init();

	if (buf == NULL)
        return -1;
    
	ret = read(fd, buf, count);
	while (ret == -1 && errno == EAGAIN) {
		uthread_yield();
		ret = read(fd, buf, count);
	}

	return ret;
}

int uthread_write(int fd, const void * buf, size_t count)
{
	int ret;
    
    uthread_init();

	if (buf == NULL)
		return -1;

	ret = write(fd, buf, count);
	while (ret == -1 && errno == EAGAIN) {
		uthread_yield();
		ret = write(fd, buf, count);
	}

	return ret;
}
